package com.lyl.cloud.controller;

import cn.hutool.core.date.DateUtil;
import com.lyl.cloud.common.base.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class ConsulController {

    public static final String PAYMENT_SERVICE = "http://cloud-consul-payment-service";
    @Value("${server.port}")
    private String serverPort;

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consulTest")
    public Result consulTest(){
        String str = DateUtil.now() + "  consulTest  端口号: " + serverPort;
        System.out.println(str);
        return Result.success(str);
    }

    @GetMapping("/consul")
    public Result consul(){
        ResponseEntity<Result> response = restTemplate.getForEntity(PAYMENT_SERVICE + "/consul", Result.class);
        if (response.getStatusCodeValue() == 200){
            System.out.println(DateUtil.now() + " consul请求成功 ");
            return response.getBody();
        }
        System.out.println(DateUtil.now() + " consul请求失败 ，状态码：" + response.getStatusCodeValue());
        return Result.fail();
    }

    @GetMapping("/discovery")
    public Result discovery(){
        List<ServiceInstance> instanceList = discoveryClient.getInstances("cloud-consul-payment-service");
        for (ServiceInstance instance : instanceList) {
            System.out.println(instance.getServiceId() + "\t" + instance.getInstanceId() + "\t" + instance.getHost() + "\t" +
                    instance.getPort() + "\t" + instance.getUri());
        }
        return Result.success(instanceList);
    }

}
